package com.ja.openchat.ui.contact;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.ja.openchat.BR;
import com.ja.openchat.ui.base.JaBaseActivity;
import com.ja.openchat.views.CustomEditText;
import com.ja.openchat.views.SideIndexBar;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.model.contact.Section;
import com.zy.openchat.core.model.contact.SectionInfo;
import com.zy.openchat.core.model.message.ChatInfo;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ja.openchat.R;
import butterknife.BindView;

public class GroupContactHomeActivity extends JaBaseActivity {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.et_search)
    CustomEditText etSearch;
    @BindView(R.id.userRecyclerView)
    RecyclerView userRecyclerView;
    @BindView(R.id.tv_ok_right)
    TextView tv_ok_right;

    private ArrayList<ChatInfo> mChooseUserInfos;
    private GroupHomeListAdapter groupListAdapter;
    private List<Section> sectionList = new ArrayList<>();
    private List<ChatInfo> localList = new ArrayList<>();
    private List<ChatInfo> totalList = new ArrayList<>();
    private CircleGroupAdapter circleUserAdapter;

    public static void chooseGroups(Activity context,int requestCode,ArrayList<ChatInfo> chatInfos){
        Intent intent = new Intent(context,GroupContactHomeActivity.class);
        if(chatInfos!=null){
            intent.putExtra("choose",chatInfos);
        }
        context.startActivityForResult(intent,requestCode);
    }


    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_group_contact;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initData() {
        setTitle(getString(R.string.group_chat));
        if(getIntent()!=null&&getIntent().getSerializableExtra("choose")!=null){
            ArrayList<ChatInfo> chatInfos = (ArrayList<ChatInfo>)getIntent().getSerializableExtra("choose");
            mChooseUserInfos = chatInfos;
        }

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        groupListAdapter = new GroupHomeListAdapter( sectionList);
        recyclerView.setAdapter(groupListAdapter);
        //加载数据
        reloadGroups();

        //点击事件
        groupListAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (sectionList != null && sectionList.size() > 0 && position >= 0 && position < sectionList.size()) {
                    Section section = sectionList.get(position);
                    Object obj =section.getObject();
                    if (obj instanceof ChatInfo){
                        ChatInfo user = (ChatInfo)obj;
                        section.setChecked(!section.isChecked());
                        if(section.isChecked()){
                            mChooseUserInfos.add(0,user);
                        }else{
                            if(!mChooseUserInfos.remove(user)){
                                if(mChooseUserInfos!=null&&mChooseUserInfos.size()>0){
                                    for(ChatInfo userInfo:mChooseUserInfos){
                                        if(userInfo.id == user.id){
                                            mChooseUserInfos.remove(userInfo);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        circleUserAdapter.notifyDataSetChanged();
                        groupListAdapter.notifyItemChanged(position);
                    }
                }
            }
        });



        etSearch.setOnXTextChangeListener(new CustomEditText.OnXTextChangeListener() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                doSearch(s.toString());
            }
        });

        if(mChooseUserInfos==null){
            mChooseUserInfos = new ArrayList<>();
        }
        circleUserAdapter = new CircleGroupAdapter(mChooseUserInfos);
        userRecyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
        userRecyclerView.setAdapter(circleUserAdapter);
        userRecyclerView.setVisibility(View.VISIBLE);
        tv_ok_right.setVisibility(View.VISIBLE);
        tv_ok_right.setText(getString(R.string.ok_text));
        tv_ok_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("users",mChooseUserInfos);
                setResult(Activity.RESULT_OK,intent);
                finish();
            }
        });
    }


    public void doSearch(String keyword){
        if(TextUtils.isEmpty(keyword)){
            resetList(totalList);
            return;
        }
        localList.clear();
        if(totalList!=null&&totalList.size()>0){
            for(ChatInfo userInfo:totalList){
                if(!TextUtils.isEmpty(userInfo.title)&&userInfo.title.contains(keyword)){
                    localList.add(userInfo);
                }
            }
        }
        resetList(localList);
    }



    private void reloadGroups() {
        sectionList.clear();
        //获取联系人
        List<ChatInfo> list = TelegramManager.getTelegramManager().getTgData().getMyGroups();
        //排序
        if (list.size() > 1) {
            Collections.sort(list, new Comparator<ChatInfo>() {
                @Override
                public int compare(ChatInfo ct1, ChatInfo ct2) {
                    if (!StringUtils.isEmpty(ct1.title_full_py) && !StringUtils.isEmpty(ct2.title_full_py)) {
                        return ct1.title_full_py.compareTo(ct2.title_full_py);
                    }
                    return 0;
                }
            });
        }
        totalList.clear();
        totalList.addAll(list);
        resetList(list);
    }

    private void resetList(List<ChatInfo> list){
        //生成a-z hash
        Map<String, List<ChatInfo>> sectionMap = new HashMap<>();
        for (String azIndex : SideIndexBar.DEFAULT_INDEX_ITEMS_1) {
            sectionMap.put(azIndex, new ArrayList<>());
        }
        //插入userinfo
        for (ChatInfo chat : list) {
            if (!StringUtils.isEmpty(chat.title_full_py)) {
                String ch = String.valueOf(chat.title_full_py.toUpperCase().charAt(0));
                if (sectionMap.get(ch) != null) {
                    sectionMap.get(ch).add(chat);
                } else {
                    sectionMap.get("#").add(chat);
                }
            } else {
                sectionMap.get("#").add(chat);
            }
        }
        //ui数据
        for (String azIndex : SideIndexBar.DEFAULT_INDEX_ITEMS_1) {
            if (sectionMap.get(azIndex).size() > 0) {
                sectionList.add(new Section(true, new SectionInfo(azIndex)));
                for (ChatInfo chat : sectionMap.get(azIndex)) {
                    boolean isChecked = false;
                    if(mChooseUserInfos!=null&&mChooseUserInfos.size()>0){
                        for(ChatInfo userInfo:mChooseUserInfos){
                            if(userInfo.id == chat.id){
                                isChecked = true;
                                break;
                            }
                        }
                    }
                    sectionList.add(new Section(false, chat,isChecked));
                }
            }
        }
        //刷新页面
        groupListAdapter.notifyDataSetChanged();
    }

    public void startRefreshTimer() {
        reloadGroups();
    }

    @Override
    protected boolean isHaveButterKnife() {
        return true;
    }

    @Override
    protected boolean isHaveEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTgEvent(final TgEvent tg_event) {
        switch (tg_event.event) {
            case EUser_Td_Contact_Photo_Ok:
            case EUser_Td_Chat_Changed:
                groupListAdapter.notifyDataSetChanged();
                break;
            case EUser_Td_Chat_List_Changed:
                startRefreshTimer();
                break;
        }
    }
}
